package com.cg.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cg.Dto.*;
import com.cg.common.StringConstant;
import com.cg.entity.Dictionarydata;
import com.cg.entity.Farm;
import com.cg.mapper.FarmMapper;
import com.cg.result.PageVO;
import com.cg.result.R;
import com.cg.service.DictionarydataService;
import com.cg.service.FarmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhy
 * @since 2024-12-26
 */
@Service
public class FarmServiceImpl extends ServiceImpl<FarmMapper, Farm> implements FarmService {
    @Resource
    private DictionarydataService dictionarydataService;

    @Override
    public R<Farm> searchs(SearchFarmDto searchFarmDto) {
        Page<Farm> page =new Page<> (searchFarmDto.getPageNumber (),searchFarmDto.getPageSize ());
        LambdaQueryWrapper<Farm> wrapper = new LambdaQueryWrapper<Farm> ()
                .like ( StringUtils.isNotBlank ( searchFarmDto.getFarmName () ), Farm::getFarmName, searchFarmDto.getFarmName () )
                .eq ( searchFarmDto.getStatus () != null, Farm::getStatus, searchFarmDto.getStatus () );
        Page<Farm> page1 = this.page ( page, wrapper );
        PageVO<Farm> pageVO =new PageVO<> ();
        BeanUtils.copyProperties (page1,pageVO);
        return R.Success (pageVO);
    }
    @Override
    public R<?> inserts(InsertFarmDto insertFarmDto) {
            // 获取所有农场记录并检查农场名称是否已存在
            List<Farm> farmList = this.list();
            if (farmList.stream().anyMatch(data -> data.getFarmName().equals(insertFarmDto.getFarmName()))) {
                return R.Failed(StringConstant.FARMNAMEISUSE);
            }
            // 检查是否需要创建新的 Dictionarydata 记录
            List<Dictionarydata> dictionaryList = dictionarydataService.list();
            Optional<Dictionarydata> existingBreedData = dictionaryList.stream()
                    .filter(data -> data.getValue().equals(insertFarmDto.getBreed()))
                    .findFirst();
            Dictionarydata dictionaryData;
            if (existingBreedData.isPresent()) {
                dictionaryData = existingBreedData.get();
            } else {
                // 创建新的 Dictionarydata 实体
                dictionaryData = new Dictionarydata();
                dictionaryData.setValue(insertFarmDto.getBreed());
                // 其他必要的初始化
                dictionarydataService.save(dictionaryData);  // 假设有一个 save 方法用于保存 Dictionarydata
            }
            // 创建新的 Farm 实体并复制属性
            Farm farm = new Farm();
            BeanUtils.copyProperties(insertFarmDto, farm);
            // 设置 dictionaryDataId 字段为匹配或新创建的 Dictionarydata 的 id
            farm.setDictionaryDataId(dictionaryData.getId());
            // 尝试保存农场信息
            save(farm);
            // 返回成功结果，包含新插入的农场 ID 和字典数据 ID
            return R.Success (StringConstant.INSERTSUCCESS);
    }
    @Override
    public R<?> updateFarm(UpdateFarmDto updateFarmDto) {
        LambdaUpdateWrapper<Farm> wrapper = new LambdaUpdateWrapper<Farm> ()
                .set ( Farm::getFarmName, updateFarmDto.getFarmName () )
                .set ( Farm::getSiteScale, updateFarmDto.getSiteScale () )
                .set ( Farm::getBreedingScale, updateFarmDto.getBreedingScale () )
                .set ( Farm::getProvince, updateFarmDto.getProvince () )
                .set ( Farm::getCity, updateFarmDto.getCity () )
                .set ( Farm::getDistrictCounty, updateFarmDto.getDistrictCounty () )
                .set ( Farm::getLocation, updateFarmDto.getLocation () )
//                .set (Farm::getDictionaryDataId,updateFarmDto.getDictionaryDataId ())
                .set (Farm::getAddress,updateFarmDto.getAddress ())
                .set ( Farm::getBreed, updateFarmDto.getBreed () )
                .eq ( Farm::getId, updateFarmDto.getId () );
        // 查询数据字典以查找现有的牲畜品种
        List<Dictionarydata> dictionaryList = dictionarydataService.list ();
        Optional<Dictionarydata> existingBreedData = dictionaryList.stream ()
                .filter ( data -> data.getValue ().equals ( updateFarmDto.getBreed () ) )
                .findFirst ();
        if (existingBreedData.isPresent ()) {
            // 如果找到了对应的品种，则使用其ID
           Integer  dictionaryDataId = existingBreedData.get ().getId ();
            // 更新wrapper以包含新的DictionaryDataId
            wrapper.set ( Farm::getDictionaryDataId, dictionaryDataId );
        } else {
            // 如果没有找到对应的品种，则不允许更新，并返回错误信息
            return R.Failed ( StringConstant.TYPENOUSE );
        }
// 执行更新操作
        boolean update = this.update ( wrapper );

        if (update) {
            return R.Success ( StringConstant.UPDATESUCCESS );
        } else {
            return R.Failed ( StringConstant.UPDATEFAILED );
        }
    }

    @Override
    public R<?> updateStatus(UpdateFramStatusDto updateFramStatusDto) {
       LambdaUpdateWrapper<Farm> wrapper =new LambdaUpdateWrapper<Farm> ()
               .set (Farm::getStatus,updateFramStatusDto.getStatus ())
               .eq (Farm::getId,updateFramStatusDto.getId ());
        boolean update = this.update (wrapper);
        if(update)
        {
            return R.Success (StringConstant.UPDATESUCCESS);
        }
           return  R.Failed(StringConstant.UPDATEFAILED);
    }

    @Override
    public R<?> searchdetail(GetInsertFramDto getInsertFramDto) {
       LambdaQueryWrapper<Farm> wrapper =new LambdaQueryWrapper<Farm> ()
               .eq (Farm::getId,getInsertFramDto.getId ());
          Farm one = this.getOne ( wrapper );
           return R.Success (one);
    }
    @Override
    public R<Farm> getFarnByStatus() {
        List<Farm> list = this.list ();
       List<Farm> list1 =list.stream ()
               .filter (farm -> farm.getStatus ()==true)
               .collect ( Collectors.toList () );
       return R.Success (list1);
    }
}
